package com.cc.demo.controller;

import com.cc.demo.entity.Message;
import com.cc.demo.service.MessageService;
import com.mybatisflex.core.paginate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;


    /**
     * 分页获取留言列表
     */
    @GetMapping
    public Page<Message> list(
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        return messageService.list(currentPage, pageSize);
    }

    /**
     * 根据ID获取留言详情
     */
    @GetMapping("/{id}")
    public Message getById(@PathVariable Long id) {
        return messageService.getById(id);
    }

    /**
     * 保存新留言
     */
    @PostMapping
    public Map<String, Object> save(@RequestBody Message message) {
        Map<String, Object> result = new HashMap<>();
        boolean success = messageService.save(message);
        result.put("success", success);
        result.put("message", success ? "留言成功" : "留言失败");
        return result;
    }

    /**
     * 更新留言
     */
    @PutMapping
    public Map<String, Object> update(@RequestBody Message message) {
        Map<String, Object> result = new HashMap<>();
        boolean success = messageService.update(message);
        result.put("success", success);
        result.put("message", success ? "更新成功" : "更新失败");
        return result;
    }

    /**
     * 删除留言（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        boolean success = messageService.deleteById(id);
        result.put("success", success);
        result.put("message", success ? "删除成功" : "删除失败");
        return result;
    }

    /**
     * 搜索留言
     */
    @GetMapping("/search")
    public Page<Message> searchByCondition(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        return messageService.searchByCondition(keyword, currentPage, pageSize);
    }
}
